package top.chukongxiang.dubboboot.simple.common.utils;

import java.io.*;

public class FileUtils {

    public static boolean writeFile(byte[] bytes, String dstPath){
        return writeFile(bytes,new File(dstPath));
    }

    public static boolean writeFile(byte[] bytes, File dstFile){
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            FileOutputStream fos = new FileOutputStream(dstFile);
            byte[] temp = new byte[1024];
            while(bais.read(temp) !=-1){
                fos.write(temp);
            }
            fos.flush();
            fos.close();
            bais.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean saveFile(byte[] bytes, String dstPath){
        return saveFile(bytes,new File(dstPath));
    }
    public static boolean saveFile(byte[] bytes, File dstFile){
        if(dstFile.exists())
            return writeFile(bytes,dstFile);
        if(dstFile.isDirectory())
            return false;
        try {
            File parentFile = dstFile.getParentFile();
            if(!parentFile.exists()) {
                parentFile.mkdirs();
            }
            dstFile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return writeFile(bytes,dstFile);
    }

    public static byte[] toByteArray(File file){
        if(!file.exists()) {
            return null;
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            return toByteArray(fileInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static byte[] toByteArray(InputStream inputStream){
        try {
            if(inputStream==null) {
                return null;
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            int n = -1;
            while((n=inputStream.read(temp))!=-1){
                byteArrayOutputStream.write(temp,0,n);
            }
            byteArrayOutputStream.close();
            inputStream.close();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getFormatWithFileName(String fileName) {
        if (fileName==null) {
            return null;
        }
        int index = fileName.lastIndexOf(".");
        if (index==-1) {
            return null;
        } else {
            return fileName.substring(index);
        }
    }

}
